﻿using AutoMapper;
using MediatR;
using Process.Api.Application.Command.BOM;
using Process.BLL;
using Process.DAL;
using Process.ErrorCod;
using Process.Model;

namespace Process.Api.Application.Handler.BOM
{
    public class UpdateGoodsinfoHandler : IRequestHandler<UpdateGoodsinfoCommand, ApiResult<int>>
    {
        private readonly IProcessRepository<Goodsinfo> goodsinfoRepo;
        private readonly IMapper mapper;

        public UpdateGoodsinfoHandler(IProcessRepository<Goodsinfo> goodsinfoRepo, IMapper mapper)
        {
            this.goodsinfoRepo = goodsinfoRepo;
            this.mapper = mapper;
        }
        /// <summary>
        /// 修改物品信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<int>> Handle(UpdateGoodsinfoCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();

            // 验证数据是否存在
            var existingData = goodsinfoRepo.GetAllAsync().FirstOrDefault(x => x.Id == request.Id && x.IsDelete == false);
            if (existingData == null)
            {
                result.Code = ErrorStatus.Fail;
                result.Message = "要修改的物品不存在或已被删除";
                result.Data = 0;
                return result;
            }

            // 检查工序编号是否重复（排除当前记录）
            var duplicateCode = goodsinfoRepo.GetAllAsync()
                .FirstOrDefault(x => x.GoodsCode == request.GoodsCode && x.Id != request.Id && x.IsDelete == false);
            if (duplicateCode != null)
            {
                result.Code = ErrorStatus.Fail;
                result.Message = "工序分类编号已存在，请使用其他编号";
                result.Data = 0;
                return result;
            }

            var model = mapper.Map(request, existingData);

            // 更新数据
            var updateResult = await goodsinfoRepo.UpdateAsync(model);

            if (updateResult > 0)
            {
                result.Code = ErrorStatus.Success;
                result.Message = "物品信息修改成功";
                result.Data = updateResult;
            }
            else
            {
                result.Code = ErrorStatus.Fail;
                result.Message = "物品信息修改失败";
                result.Data = 0;
            }
            return result;
        }
    }
}
